package cn.weakup.thread.semaphore;

import java.util.concurrent.*;

/**
 * @author Dawn
 * @version 1.0.0
 * @desc Semaphore样例代码
 * @date 2022/5/8
 */
public class TryAcquireExample {

    private static final int threadCount = 20;

    public static void main(String[] args) {
        ExecutorService executor = new ThreadPoolExecutor(8, 16, 10,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000), new ThreadPoolExecutor.AbortPolicy());

        Semaphore semaphore = new Semaphore(4);

        for (int i = 0; i < threadCount; i++) {
            int finalI = i;
            executor.execute(() -> {
                try {
                    // 尝试获取一个许可，超时丢弃任务
                    if(semaphore.tryAcquire(1010, TimeUnit.MILLISECONDS)){
                        test(finalI);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            });
        }
        executor.shutdown();
    }

    private static void test(int threadNum) throws InterruptedException {
        System.out.println("当前执行线程编号：" + threadNum);
        TimeUnit.SECONDS.sleep(1);
    }
}
